package com.salesmanager.web.admin.controller.reports;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperPrint;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.salesmanager.core.business.merchant.model.MerchantStore;
import com.salesmanager.core.business.order.model.orderstatus.OrderStatus;
import com.salesmanager.core.business.reference.language.model.Language;
import com.salesmanager.core.business.report.service.JasperReportService;
import com.salesmanager.web.admin.controller.ControllerConstants;
import com.salesmanager.web.admin.entity.web.Menu;
import com.salesmanager.web.constants.Constants;
import com.salesmanager.web.utils.LocaleUtils;

@Controller
public class ExportReportController {
	private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

	@Autowired
	private JasperReportService jasperReportService;

	private static final Logger LOGGER = LoggerFactory.getLogger(ExportReportController.class);

	@PreAuthorize("hasRole('ORDER')")
	@RequestMapping(value = "/admin/reports/export.html", method = RequestMethod.GET)
	public String displayExportReport(Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setMenu(model, request);
		request.setAttribute("toDate", dateFormat.format(new Date()));
		request.setAttribute("orderStatusList", Arrays.asList(OrderStatus.values()));     
		return ControllerConstants.Tiles.Report.exportReportView;
	}

	@PreAuthorize("hasRole('ORDER')")
	@RequestMapping(value = "/admin/reports/export.html", method = RequestMethod.POST)
	public String renderExportReport(Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setMenu(model, request);
		MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE);
		String fromDate = request.getParameter("fromDate");
		String toDate = request.getParameter("toDate");
		String orderStatus = request.getParameter("orderStatus");
		String pageIndex = request.getParameter("pageIndex");
		
		int index = Integer.parseInt(pageIndex);
		
		if(StringUtils.isEmpty(orderStatus))
			orderStatus = null;
		
		Map<String, Object> parameters = new HashMap<String, Object>();
		Date from = null;
		Date to = null;

		if (StringUtils.isNotEmpty(fromDate))
			from = dateFormat.parse(fromDate);

		if (StringUtils.isNotEmpty(toDate))
			to = dateFormat.parse(toDate);

		parameters.put("fromDate", from);
		parameters.put("toDate", to);
		parameters.put("status", orderStatus);
		parameters.put("hideHeader", "");
		parameters.put("REPORT_LOCALE", new Locale("vi"));
		
		JasperPrint print = jasperReportService.fillReport(ReportController.class
				.getResourceAsStream("/report/Export.jasper"), parameters);
		
		if(print.getPages().size()==1){
			// modify height to fix total rows
			int rows = print.getPages().get(0).getElements().size();
			
		}
		String responseHtml = new String(
				jasperReportService.exportToHtml(print, index-1), "UTF-8");
		
		
		
		int fromIndex = responseHtml.indexOf("<body");
		fromIndex = responseHtml.indexOf(">", fromIndex);
		int toIndex = responseHtml.indexOf("</body>");
		
		request.setAttribute("result", responseHtml.substring(fromIndex + 1, toIndex));
		request.setAttribute("fromDate", fromDate);
		request.setAttribute("toDate", toDate);
		request.setAttribute("orderStatus", orderStatus);
		request.setAttribute("pageSize", print.getPages().size());
		request.setAttribute("pageIndex", index);
		request.setAttribute("orderStatusList", Arrays.asList(OrderStatus.values()));
		return ControllerConstants.Tiles.Report.exportReportView;
	}

	@PreAuthorize("hasRole('REPORT')")
	@RequestMapping(value = "/admin/reports/export/pdf.html", method = RequestMethod.GET)
	public void renderExportPdfReport(Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setMenu(model, request);
		String fromDate = request.getParameter("fromDate");
		String toDate = request.getParameter("toDate");
		String orderStatus = request.getParameter("orderStatus");
		String hideHeader = request.getParameter("hideHeader");
		Map<String, Object> parameters = new HashMap<String, Object>();

		Date from = null;
		Date to = null;

		if (StringUtils.isNotEmpty(fromDate))
			from = dateFormat.parse(fromDate);

		if (StringUtils.isNotEmpty(toDate))
			to = dateFormat.parse(toDate);

		if(StringUtils.isEmpty(orderStatus))
			orderStatus = null;
		
		parameters.put("fromDate", from);
		parameters.put("toDate", to);
		parameters.put("status", orderStatus);
		parameters.put("hideHeader", hideHeader);
		parameters.put("REPORT_LOCALE", new Locale("vi"));
		JasperPrint print = jasperReportService.fillReport(ReportController.class
						.getResourceAsStream("/report/Export.jasper"), parameters);

		byte[] result = jasperReportService.exportToPdf(print);
		response.setContentType("application/pdf;charset=UTF-8");
		
		String fileName = "Export_Report_" + dateFormat.format(new Date()) + ".pdf";
		response.setHeader("Content-Disposition", "attachment; filename="
				+ fileName);
		response.getOutputStream().write(result);
		response.flushBuffer();
	}

	@PreAuthorize("hasRole('REPORT')")
	@RequestMapping(value = "/admin/reports/export/excel.html", method = RequestMethod.GET)
	public void renderExportExcelReport(Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setMenu(model, request);
		String fromDate = request.getParameter("fromDate");
		String toDate = request.getParameter("toDate");
		String orderStatus = request.getParameter("orderStatus");
		Map<String, Object> parameters = new HashMap<String, Object>();
		Date from = null;
		Date to = null;

		if (StringUtils.isNotEmpty(fromDate))
			from = dateFormat.parse(fromDate);

		if (StringUtils.isNotEmpty(toDate))
			to = dateFormat.parse(toDate);

		if(StringUtils.isEmpty(orderStatus))
			orderStatus = null;
		parameters.put("fromDate", from);
		parameters.put("toDate", to);
		parameters.put("status", orderStatus);
		parameters.put("REPORT_LOCALE", new Locale("vi"));
		parameters.put(JRParameter.IS_IGNORE_PAGINATION, true);
		
		JasperPrint print = jasperReportService.fillReport(ReportController.class
						.getResourceAsStream("/report/Export.jasper"), parameters);

		byte[] result = jasperReportService.exportToExcel(print);
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		String fileName = "Export_Report_" + dateFormat.format(new Date())
				+ ".xls";
		response.setHeader("Content-Disposition", "attachment; filename="
				+ fileName);
		response.getOutputStream().write(result);
		response.flushBuffer();
	}

	private void setMenu(Model model, HttpServletRequest request)
			throws Exception {
		// display menu
		Map<String, String> activeMenus = new HashMap<String, String>();
		activeMenus.put("report", "report");
		activeMenus.put("report-list", "report-list");

		@SuppressWarnings("unchecked")
		Map<String, Menu> menus = (Map<String, Menu>) request
				.getAttribute("MENUMAP");

		Menu currentMenu = (Menu) menus.get("report");
		model.addAttribute("currentMenu", currentMenu);
		model.addAttribute("activeMenus", activeMenus);
	}
}
